<?php
/**
 * Created by PhpStorm.
 * User: sh01
 * Date: 2018/1/9
 * Time: 9:26
 */

namespace corpWeixin\corpWeixinSdk;
require_once 'WXBizMsgCrypt.php';

class CWXTool
{
    public $crypt; //sdk消息加解密工具类
    private $token = '';
    private $encodingAesKey = '';
    private $corpId = '';
    private $agentId = '';
    private $agentSecret = '';
    private $accessTokenDir = '';
    private $redirect_url = '';
    private static $instance;
    private function __construct($config)
    {
        $this->token = $config['token'];
        $this->encodingAesKey = $config['encodingAesKey'];
        $this->corpId = $config['corpId'];
        $this->agentId = $config['agentId'];
        $this->agentSecret = $config['agentSecret'];
        $this->accessTokenDir = $config['accessTokenDir'];
        $this->redirect_url = $config['redirect_url'];
        $this->crypt = new \WXBizMsgCrypt($this->token,$this->encodingAesKey,$this->corpId);
    }

    /**
     * 创建单例
     * @param $config
     * @return CWXTool
     */
    public static function create($config)
    {
        if(!isset(self::$instance))
        {
            self::$instance = new CWXTool($config);
        }
        return self::$instance;
    }

    public static function getInstance()
    {
        if(!isset(self::$instance))
            die('实例不存在，请先使用getInstance方法创建CWXTool的单例');
        return self::$instance;
    }



    /**
     * 生成明文xml文本消息（该方法返回明文消息字符串，需要作为encryptMsg()方法的参数之一再加密成待发送消息）
     * @param $toUser
     * @param $fromUser
     * @param $content
     * @return string
     */
    public function xmlMessage($fromUser, $toUser, $content)
    {
        $xmlFormat = '<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>';
        return sprintf($xmlFormat, $toUser, $fromUser, time(), $content);

    }
/*主动请求接口方法封装*/

    /**
     * 生成主动发送消息的json格式（此返回值须以post方式请求微信接口）
     * @param array $msgBody
     * @param string $msgType
     * @param string $toUsers 最多支持1000个接收用户
     * @param array $toParties 最多支付100个部门
     * @param array $toTags 最多支付100个标签
     * @return string
     */
    public function jsonMessage($msgBody = array(),$msgType = 'text',$toUsers = '@all',$toParties=[],$toTags=[])
    {
        $postData = [
           'touser'=>($toUsers==='@all')?$toUsers:join('|',$toUsers), //非必填 @all为向全体发送，此时以下两个参数忽略
           'toparty'=>join('|',$toParties), //非必填
           'totag'=>join('|',$toTags), //非必填
           'msgtype'=>$msgType, //必填
           'agentid'=>$this->agentId, //必填
            $msgType=>$msgBody,
           'safe'=>0, //0：不保密 1：保密 非必填
       ];
        return json_encode($postData);
    }


    /**
     * 请求微信平台获取accessToken接口并返回accessToken
     * @return bool|mixed
     */
    private function writeFileAccessToken()
    {
        // 如果是企业号用以下URL获取access_token
        $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->corpId&corpsecret=$this->agentSecret";
        $res = json_decode(Curl::httpGet($url),false);
        $access_token = $res->access_token;
        if ($access_token) {
            $data['expire_time'] = time() + 7000;
            $data['access_token'] = $access_token;
            file_put_contents($this->accessTokenDir."/access_token.php", "<?php exit();?> ".json_encode($data));
            return $access_token;
        }
        return false;
    }

    /**
     * 程序获取accessToken值
     * @return bool|mixed
     */
    public function getAccessToken() {
        $access_token_file = $this->accessTokenDir."/access_token.php";
        //自动建立存放accessToken的目录
        if(!is_dir($this->accessTokenDir))
            @mkdir($this->accessTokenDir, 0777);
        //获取accessToken
        $access_token_data = array();
        if(is_file($access_token_file)) //如果access_token.php文件存在，则读取accessToken数据
        {
            $content = trim(substr(file_get_contents($access_token_file), 15));
            $access_token_data = json_decode($content,true);
        }
        //如果读取到有效accessToken数据，则直接返回accessToken
        if($access_token_data && $access_token_data['expire_time'] > time())
            return $access_token_data['access_token'];
        else //没有读取到有效数据则重写则accessToken文件
        {
            if($access_token = $this->writeFileAccessToken())
                return $access_token;
        }
        return false;
    }

    /**
     * 微信平台登录页面，登录完会跳到在平台设定域名下，并在以下URL中配置的企业应用方页面URL
     * @return string
     */
    public function getOauthUrl()
    {
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->corpId
            .'&redirect_uri='.$this->redirect_url
            .'&response_type=code&scope=snsapi_privateinfo&agentid='.$this->agentId
            .'&state=customContent#wechat_redirect';
        return $url;
    }
}